#!/bin/bash

get_gpio()
{
    local NET_NAME=$1
    local RET_VAL

    mapfile -t -d " " GPIO_INFO < <(gpiofind "$NET_NAME")
    if [ "${#GPIO_INFO[@]}" -ne 2 ]; then
        echo "get_gpio: can not find gpio, $NET_NAME" >&2
        return 1
    fi
    if ! RET_VAL=$(gpioget "${GPIO_INFO[0]}" "${GPIO_INFO[1]%$'\n'}") ; then
        echo "get_gpio: get ${NET_NAME} failed" >&2
        return 1
    fi
    echo "${RET_VAL}"
    return 0
}

set_gpio()
{
    local NET_NAME=$1
    local OUT_VAL=$2
    mapfile -t -d " " GPIO_INFO < <(gpiofind "$NET_NAME")
    if [ "${#GPIO_INFO[@]}" -ne 2 ]; then
        echo "set_gpio: can not find gpio, $NET_NAME"
        return 1
    fi

    echo -n "set_gpio: set $NET_NAME = $OUT_VAL"
    if ! gpioset "${GPIO_INFO[0]}" "${GPIO_INFO[1]%$'\n'}"="$OUT_VAL"; then
        echo " failed"
        return 1
    fi

    echo " success"
    return 0
}

bind_i2c_device()
{
    DRIVER_NAME="$1"
    DEV_BUS_ADDR="$2"
    DRIVER_DIR_PATH="/sys/bus/i2c/drivers/${DRIVER_NAME}"
    DRIVER_BIND_PATH="${DRIVER_DIR_PATH}/bind"
    if [ ! -L "${DRIVER_DIR_PATH}/${DEV_BUS_ADDR}" ]; then
        echo "bind_i2c_device: $DRIVER_NAME, $DEV_BUS_ADDR"
        echo "${DEV_BUS_ADDR}" > "${DRIVER_BIND_PATH}"
    fi
}
